<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/31
 * Time: 9:29
 */

namespace app\common\controller;

use think\Request;

/**
 * Class ClientAuth
 * @package app\common\controller
 *
 * @property string appId
 * @property string appSecret
 * @property string iosToken
 *
 * @property Request request
 */
final class ClientAuth
{
    const APP_ID_WECHAT = 1;
    const APP_ID_APP = 2;
    const APP_ID_PC = 3;
    const APP_SECRET = [
        self::APP_ID_WECHAT => '39b3567d0b8ac89c025b78beec26acb0',
        self::APP_ID_APP    => '335a42771860bfb06dceb79f531f8de7',
        self::APP_ID_PC     => '335a42771860bfb06dceb49f531f8de7',
    ];

    private $appId;
    private $appSecret;

    private $request;

    public function __construct()
    {
        $this->request = Request::instance();

        $appId = $this->request->header('appid');
        if (is_null($appId)) $appId = $this->request->param('appid');
        $appSecret = $this->request->header('appsecret');
        if (is_null($appSecret)) $appSecret = $this->request->param('appsecret');

        $iosToken = $this->request->header('iostoken');
        if (is_null($iosToken)) $iosToken = $this->request->param('iostoken');
        $this->iosToken = self::IOS_TOKEN===$iosToken ? $iosToken : null;

        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function auth($forceVerify = true) {

        // 检查appId和appSecret
        if (empty($this->appId) || empty($this->appSecret)) {
            $this->invalidRequest($forceVerify);
        } elseif (isset(self::APP_SECRET[$this->appId]) == false) {
            $this->invalidRequest($forceVerify);
        } elseif (self::APP_SECRET[$this->appId] !== $this->appSecret) {
            $this->invalidRequest($forceVerify);
        }

    }

    public function isPC() {
        return self::APP_ID_PC == $this->appId;
    }
    public function isAPP() {
        return self::APP_ID_APP == $this->appId;
    }
    public function isWECHAT() {
        return self::APP_ID_WECHAT == $this->appId;
    }

    public function isIOS() {
        return self::IOS_TOKEN === $this->iosToken;
    }

    const IOS_TOKEN = 'e7bdf33a3fceca6073e9e52ff2c65b1c2130d2f3d2be43c9e362f152bf1bd43a';
    /**
     * iOS专用接口鉴权
     */
    public function iOSVerify() {
        if (self::IOS_TOKEN !== $this->iosToken) {
            $this->invalidRequest(true);
        }
    }

    /**
     * 直接响应400
     * @param bool $forceVerify
     */
    protected function invalidRequest($forceVerify) {
        if ($forceVerify) {
            header('Content-Type: application/json; charset=utf8');
            echo json_encode(array('code'=>400, 'msg'=>'请求无效', 'data'=>null));
            exit;
        } else {
            $this->appId = null;
            $this->appSecret = null;
        }
    }

}